package com.gradle.sample;

import com.gradle.sample.vo.User;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Query;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

public class LoginServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(LoginServlet.class);
    
    private WebApplicationContext springContext;
    
    @Override
    public void init() throws ServletException {
        //获取在web.xml中启动Spring容器
        springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
        logger.info("获取到web.xml中启动Spring容器。{}", springContext.getClass());
    }
    
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
        doGet(req,rsp);
    }
    
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
        assert springContext != null;
        
        rsp.setContentType("application/json;charset=utf-8");
        
        String email = req.getParameter("email");
        String pwd = req.getParameter("pwd");
        
        assert email != null;
        assert pwd != null;
        
        StringBuilder json = new StringBuilder("{");
        
        if (email == null || pwd == null) {
            logger.error("[{}]input of email or pwd is NULL [{} & {}].", email, pwd);
            json.append("\"login\":\"0\"");
            
            json.append("}");
            rsp.getWriter().write(json.toString());
            return;
        }
        
        String xmlStr = springContext.getBean("xmlStr", String.class);
        
        
        
        try {
            Map users = springContext.getBean("userTable", Map.class);
            logger.debug("Get the users Map.");
            
            if (pwd.equals(users.get(email))) {
                json.append("\"login\":\"1\"");
                logger.debug("user[{}] login success.", email);
            } else {
                json.append("\"login\":\"0\"");
                logger.debug("user[{}] login fail.", email);
            }
            
            json.append(",");
        } catch (Exception anyEx) {
            logger.error("Can't get users Map cause {}:{}", anyEx.getClass().getName(), anyEx.getMessage());
        }
        
        json.append(String.format("\"email\":\"%s\"", new StringBuilder(email).reverse()));
        json.append(",");
        json.append(String.format("\"pwd\":\"%s\"", new StringBuilder(pwd).reverse()));
        
        
        
        json.append("}").append(xmlStr);
        rsp.getWriter().write(json.toString());
        
        try {
            logger.debug("Try to (lookIntoHibernate)");
            lookIntoHibernate ();
        } catch (Exception anyEx) {
            logger.error("Can't (lookIntoHibernate) cause {}:{}", anyEx.getClass().getName(), anyEx.getMessage());
        }
        
        try {
            logger.debug("Try to (lookIntoDB)");
            lookIntoDB ();
        } catch (Exception anyEx) {
            logger.error("Can't (lookIntoDB) cause {}:{}", anyEx.getClass().getName(), anyEx.getMessage());
        }
    }
    
    void lookIntoSpring () {
        assert springContext != null;
    }
    
    void lookIntoHibernate () {
        assert springContext != null;
        
        Configuration hibConf = springContext.getBean("oHibntCf_inIOC", Configuration.class);
        logger.info("Get Hibernate Conf.[{}] ", hibConf);
        
        SessionFactory hibSessionF = springContext.getBean("oORM_sessionFactory", SessionFactory.class);
        logger.info("Get Hibernate SessionFactory.[{}] ", hibSessionF);
        
    }
    
    void lookIntoDB () {
        SessionFactory hibSessionF = springContext.getBean("oORM_sessionFactory", SessionFactory.class);
        
        Session session = null;
        
        User user = new User();
        user.setEmail("792626757@qq.com");
        user.setPassword("123");
        user.setSignDate(new Date());
        logger.debug("Try to save/update user[792626757@qq.com]{{}}", user);
        
        try {
            session = hibSessionF.openSession();
            
            //开启事务
            session.beginTransaction();
            //保存User对象
            session.saveOrUpdate(user);            
            //提交事务
            session.getTransaction().commit();
            
            logger.info("Save/Update user[792626757@qq.com]{{}}", user);
            
            user = null;
            Object result_usr = null;
            Query qury = session.createSQLQuery("SELECT * FROM t_user_basic").addEntity(User.class).setMaxResults(1);
            result_usr = qury.uniqueResult();
            
            logger.info("[SELECT * FROM t_user_basic]={{}}", result_usr);
        }catch(Exception e) {
            logger.error("Fail(so rollback) to save/update user[792626757@qq.com]{{}}", user);
            logger.error("{}", e.getMessage());
            e.printStackTrace();
            //回滚事务
            session.getTransaction().rollback();
        }finally {
            if (session != null) {
                if (session.isOpen()) {
                    //关闭session
                    session.close();
                }
            }
        }
    }
}